﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RN.ERP.Web.OrderService;
using RN.ERP.Web.ModelService;
using Fly.Common.Linq;
using Newtonsoft.Json;
using Telerik.Web.UI;
using System.Data;
using System.Web.Services;

namespace RN.ERP.Web.Pay
{
    public partial class ZBPayList : BasePage
    {
        OrderServiceClient client = new OrderServiceClient();
        private void BindData()
        {
            int PageIndex = int.Parse(hidPageIndex.Value);
            int PageSize = int.Parse(hidPageSize.Value);
            QueryZBTenderInfoCondition queryCondition = new QueryZBTenderInfoCondition();
            if (!string.IsNullOrEmpty(txtCorpDl.Text.Trim()))
            {
                queryCondition.CorpName = new ParameterValue<string>() { V = txtCorpDl.Text.Trim(), O = OptEnum.Like };
            }
            if (!string.IsNullOrEmpty(txtBegin.Text.Trim()) && !string.IsNullOrEmpty(txtEnd.Text.Trim()))
            {
                var date1 = new ParameterValue<DateTime?>() { V = DateTime.Parse(txtBegin.Text.Trim()), O = OptEnum.GreaterThanOrEqual };
                var date2 = new ParameterValue<DateTime?>() { V = DateTime.Parse(txtEnd.Text.Trim()).AddDays(1), O = OptEnum.LessThan };
                var list = new List<ParameterValue<DateTime?>>();
                list.Add(date1);
                list.Add(date2);
                queryCondition.OptDate = new ParameterValues<DateTime?>()
                {
                    Logic = LogicEnum.And,
                    Values = list
                };
            }
            else if (!string.IsNullOrEmpty(txtBegin.Text.Trim()))
            {
                queryCondition.OptDate1 = new ParameterValue<DateTime?>() { V = DateTime.Parse(txtBegin.Text.Trim()), O = OptEnum.GreaterThanOrEqual };
            }
            else if (!string.IsNullOrEmpty(txtEnd.Text.Trim()))
            {
                queryCondition.OptDate1 = new ParameterValue<DateTime?>() { V = DateTime.Parse(txtEnd.Text.Trim()).AddDays(1), O = OptEnum.LessThan };
            }
            if (!string.IsNullOrEmpty(txtProject.Text.Trim()))
            {
                queryCondition.ProjectName = new ParameterValue<string>() { V = txtProject.Text.Trim(), O = OptEnum.Like };
            }
            if (!string.IsNullOrEmpty(txtCorpBm.Text.Trim()))
            {
                queryCondition.CorpName1 = new ParameterValue<string>() { V = txtCorpBm.Text.Trim(), O = OptEnum.Like };
            }
            if (!string.IsNullOrEmpty(txtOrdID.Text.Trim()))
            {
                queryCondition.OrderId = new ParameterValue<string>() { V = txtOrdID.Text.Trim(), O = OptEnum.Like };
            }
            if (ddlProcess.SelectedValue != "-1")
            {
                queryCondition.FinanceProcessed = new ParameterValue<bool?>() { V = bool.Parse(ddlProcess.SelectedValue), O = OptEnum.Equal };
            }

            if (!string.IsNullOrEmpty(ucArea.AreaCode))
            {
                queryCondition.AreaCode = new ParameterValue<string>() { V = ucArea.AreaCode, O = OptEnum.StartWith };
            }
            List<QueryZBTenderInfoCondition> queryList = new List<QueryZBTenderInfoCondition>();
            queryList.Add(queryCondition);
            string resultCount = client.GetZBPayCount(JsonConvert.SerializeObject(queryList));
            string[] strs = resultCount.Split('&');
            hidPay.Value = strs[1];
            hidOut.Value = strs[2];
            List<ModelService.ZBTenderPay> result = JsonConvert.DeserializeObject<List<ModelService.ZBTenderPay>>(client.GetZBPayList(JsonConvert.SerializeObject(queryList), PageIndex, PageSize));
            lbCount.Text = strs[0];
            if (PageSize != 0)
            {
                hidPageCount.Value = (int.Parse(strs[0]) % PageSize) == 0 ? (int.Parse(strs[0]) / PageSize).ToString() : (int.Parse(strs[0]) / PageSize + 1).ToString();
            }
            GridView1.DataSource = result;
            GridView1.DataBind();
            lblPageIndex.Text = (PageIndex + 1).ToString();
            lblPageCount.Text = hidPageCount.Value;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(ucArea.AreaCode))
            {
                ucArea.AreaCode = ucArea.AreaCode;
            }
            if (!IsPostBack)
            {
                BindData();
                hidPageIndex.Value = "0";
            }
        }

        public void lbExport_Click(object sender, EventArgs e)
        {
            ExportToExcel();
        }

        #region GridView1相关

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["onmouseover"] = "e=this.style.backgroundColor;this.style.backgroundColor='#eaeaea'";
                e.Row.Attributes["onmouseout"] = "this.style.backgroundColor=e";
                e.Row.Attributes["style"] = "Cursor:pointer";
            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[0].Text = "<b>合计</b>";
                e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Center;
                List<ModelService.ZBTenderPay> list = GridView1.DataSource as List<ModelService.ZBTenderPay>;
                if (list != null)
                {
                    //总计
                    string counts = hidPay.Value;
                    string outs = hidOut.Value;
                    e.Row.Cells[6].Text = "<b>" + int.Parse(counts).ToString() + "</b>";
                    e.Row.Cells[6].HorizontalAlign = HorizontalAlign.Center;
                    e.Row.Cells[8].Text = "<b>" + int.Parse(outs).ToString() + "</b>";
                    e.Row.Cells[8].HorizontalAlign = HorizontalAlign.Center;

                }
            }
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            BindData();
        }

        protected void btnFirst_Click(object sender, EventArgs e)
        {
            int PageIndex = int.Parse(hidPageIndex.Value);
            int PageCount = int.Parse(hidPageCount.Value);
            if (PageCount > 0)
            {
                switch (((LinkButton)sender).CommandArgument.ToString())
                {
                    case "first":
                        PageIndex = 0;
                        break;
                    case "last":
                        PageIndex = PageCount - 1;
                        break;
                    case "prev":
                        if (!(PageIndex == 0))
                        {
                            PageIndex = PageIndex - 1;
                        }
                        break;
                    case "next":
                        if (!(PageIndex == (PageCount - 1)))
                        {
                            PageIndex = PageIndex + 1;
                        }
                        break;
                    case "go":
                        {
                            GridViewRow gvr = GridView1.BottomPagerRow;
                            TextBox temp = (TextBox)gvr.FindControl("txtNewPageIndex");
                            int res = Convert.ToInt32(temp.Text.ToString());
                            if (res > 0 && res < PageCount + 1)
                            {
                                PageIndex = res - 1;
                            }
                        }
                        break;
                }
                hidPageIndex.Value = PageIndex.ToString();
                BindData();
            }
        }

        #endregion GridView1相关
        private void ExportToExcel()
        {
            string style = @"<style> td { mso-number-format:\@; } </style> ";
            string pSize = hidPageSize.Value;
            hidPageIndex.Value = "0";
            hidPageSize.Value = "0";
            GridView1.PageIndex = 0;
            GridView1.AllowPaging = false;
            BindData();
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "GB2312";
            Response.AppendHeader("Content-Disposition", "attachment;filename=ZBList.xls");
            // 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码！！！
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            this.GridView1.RenderControl(oHtmlTextWriter);

            Response.Output.Write("<meta http-equiv=Content-Type content=text/html;charset=UTF-8>");
            Response.Output.Write(Server.HtmlDecode(style));//把css添加到输出流
            Response.Output.Write(Server.HtmlDecode(oStringWriter.ToString()));

            Response.Flush();
            Response.End();

            hidPageSize.Value = pSize;
            GridView1.AllowPaging = true;
            BindData();
        }
        //必须的，导出到EXCEL容错
        public override void VerifyRenderingInServerForm(Control control)
        {

        }

        protected void lbSearch_Click(object sender, EventArgs e)
        {
            hidPageIndex.Value = "0";
            BindData();
        }

        [WebMethod]
        public static string ShowRemark(object id, object type)
        {
            string ret = null;
            using (OrderServiceClient client = new OrderServiceClient())
            {
                OperationResult result = JsonConvert.DeserializeObject<OperationResult>(client.GetZBRemark(int.Parse(id.ToString()), int.Parse(type.ToString())));
                if (result.Result)
                {
                    ret = JsonConvert.SerializeObject(new { Message = result.Message });
                }
                else
                {
                    ret = JsonConvert.SerializeObject(new { Message = "操作失败" });
                }
            }
            return ret;
        }

        [WebMethod]
        public static string AddRemark(object id, object type, object check, object remark)
        {
            string ret = null;
            bool ck = false;
            if (check != null && check.ToString() == "checked")
            {
                ck = true;
            }
            using (OrderServiceClient client = new OrderServiceClient())
            {
                OperationResult result = JsonConvert.DeserializeObject<OperationResult>(client.PaySaveZBRemark(int.Parse(id.ToString()), ck, remark.ToString(), int.Parse(type.ToString())));
                if (result.Result)
                {
                    ret = JsonConvert.SerializeObject(new { Message = "操作成功" });
                }
                else
                {
                    ret = JsonConvert.SerializeObject(new { Message = "操作失败" });
                }
            }
            return ret;
        }
    }
}